package cn.wegoteam.shop.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.wegoteam.alipay.AlipayConfig;
import cn.wegoteam.alipay.AlipayNotify;
import cn.wegoteam.alipay.AlipaySubmit;
import cn.wegoteam.shop.cache.StaticDataCache;
import cn.wegoteam.shop.inter.PayImpServiceInter;
import cn.wegoteam.shop.inter.PayServiceInter;
import cn.wegoteam.shop.po.Order;
import cn.wegoteam.shop.po.User;
import cn.wegoteam.shop.util.Const;
public class AlipayService implements PayImpServiceInter {
	/**
	 * ***************************************支付宝支付pay******************************************
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String pay(Order order,User user,HttpServletRequest request){
		Map<String, String> sParaTemp = new HashMap<String, String>();
		//把请求参数打包成数组
		//支付类型 
		String baseUrl=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
		sParaTemp.put("payment_type", "1");
		sParaTemp.put("notify_url", baseUrl+StaticDataCache.getStaticdata(Const.STATIC_ALIPAY).getLink());
		sParaTemp.put("return_url", baseUrl+StaticDataCache.getStaticdata(Const.STATIC_ALIPAY).getValue());
		//卖家支付宝帐户 //必填
		sParaTemp.put("seller_email", AlipayConfig.seller_email);
		//商户网站订单系统中唯一订单号，必填 out_trade_no
		sParaTemp.put("out_trade_no", order.getOrderNumber());
		//订单名称  //必填
		sParaTemp.put("subject", AlipayConfig.subject);
		//付款金额
		sParaTemp.put("total_fee", order.getFreAndTotal());
		//订单描述
		sParaTemp.put("body", "");
		//商品展示地址 show_url 需以http://开头的完整路径，如：http://www.xxx.com/myorder.html
		sParaTemp.put("show_url", baseUrl+AlipayConfig.show_url+order.getId());
		//防钓鱼时间戳
		sParaTemp.put("anti_phishing_key", "");
		//若要使用请调用类文件submit中的query_timestamp函数
		sParaTemp.put("exter_invoke_ip", "");
		//非局域网的外网IP地址，如：221.0.0.1
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", AlipayConfig.partner);
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType( "text/html" );
		response.setCharacterEncoding( "UTF-8" );
		PrintWriter out =null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		out.println(sHtmlText);
		out.flush();
		out.close();
		return null;
}
	/**
	 * ***************************************支付宝支付return_url******************************************
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String payReturn(PayServiceInter payService,HttpServletRequest request){
		String succMess="";
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			params.put(name, valueStr);
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号

		String out_trade_no = request.getParameter("out_trade_no");

		//支付宝交易号
		String trade_no =request.getParameter("trade_no");

		//交易状态
		String trade_status =request.getParameter("trade_status");
		
		//买家支付宝
		String buyer_email =request.getParameter("buyer_email");

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		
		//计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params);
		if(verify_result){//验证成功
			succMess = handle(payService,request, out_trade_no+"", trade_no,
					trade_status, buyer_email);
		}else{
			//该页面可做页面美工编辑
			succMess="支付失败";
		}
		return succMess;
	}
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String handle(PayServiceInter payService,HttpServletRequest request,
			String out_trade_no, String trade_no, String trade_status,
			String buyer_email){
		if(trade_status.equals("TRADE_SUCCESS")||trade_status.equals("TRADE_FINISHED")){
			payService.paySuccess(request, out_trade_no, trade_no, buyer_email);
			return "支付成功";
		}
		return "抱歉，操作失败，连接已失效或重复支付，如有问题请联系客服";
	}
	

	boolean notNull(Object o){
		if(o!=null&&!o.toString().trim().equals(""))
			return true;
		return false;
		
	}
}
